#!/usr/bin/python
"""Tweaker for the VP8 codec.

Usage: vp8tweaker [--loop] <rate> <videofile>

This script consults the run database for the VP8 codec,
picks the best encoding so far, generates the tweak set for it,
finds the encoding with the highest likely score that hasn't been
encoded, executes the encoding, and reports whether or not there
was improvement.
"""

import argparse
import sys

import encoder
import pick_codec

def main():
  parser = argparse.ArgumentParser()
  parser.add_argument('rate')
  parser.add_argument('videofile')
  parser.add_argument("--loop", action="store_true", dest="loop")
  parser.add_argument("--until_score", type=float)
  parser.add_argument("--codec")
  args = parser.parse_args()

  print "Loop is", args.loop
  print "Until score is", args.until_score

  videofile = encoder.Videofile(args.videofile)

  bitrate = int(args.rate)
  args = parser.parse_args()

  print "Loop is", args.loop
  print "Codec is", args.codec

  videofile = encoder.Videofile(args.videofile)

  codec = pick_codec.PickCodec(args.codec)

  while True:
    bestsofar = codec.BestEncoding(bitrate, videofile)
    bestsofar.Recover()
    print "Starting from", bestsofar.encoder.Hashname(), \
           "score", bestsofar.Score()
    if bestsofar.Score():
      if args.until_score and bestsofar.Score() > args.until_score:
        print "Happy with the score achieved"
        return 0
      variants = bestsofar.SomeUntriedVariants()
      next_encoding = variants.BestGuess()
      if not next_encoding:
        print "Ran out of variants to try"
        return 1
    else:
      print "Best so far is unscored, trying it"
      next_encoding = bestsofar
    print "Trying encoder", next_encoding.encoder.Hashname()
    next_encoding.Execute()
    print "Score is", next_encoding.Score()
    next_encoding.Store()
    if not args.loop:
      return 0

if __name__ == '__main__':
  sys.exit(main())

